package track_code
import grails.web.JSONBuilder

class AdminController {

    protected static final String SUCCESS = true;

    protected static final String ERROR = false;

    protected def adminService;

    private renderJSON(resultCode, message, value) {
        def json = new JSONBuilder().build {
            result = resultCode
            msg = message
            data = value
        }.toString()
        log.debug(params.jsoncallback + "(" + json + ")")
        render params.jsoncallback + "(" + json + ")"
    }

    protected success(message, value) {
        renderJSON(SUCCESS, message, value)
    }

    protected error(message, value) {
        renderJSON(ERROR, message, value)
    }

    def AdminController() {
        log.debug(params);
    }
    
    def index() {
    }

    /**
     * 注册用户
     */
    def registerUser() {
        def result = false;
        def errorStr = "注册失败，未知错误";
        try {
            def username = params.username;
            def password = params.password;
            
            if (username || password) {
                errorStr = "请填写完成";
            } else if (TrackUser.findByUsername(username)) {
                errorStr = "用户名已经存在";
            } else {
                def trackUser = new TrackUser(params);
                if (trackUser) {
                    result = true;
                }
            }
        } catch(Exception e) {
            log.error(e);
        } finally {
            if (result) {
                success("", null);
            } else {
                error(errorStr, null);
            }
        }
    }

    /**
     * 后台登录
     */
    def login() {
        def result = false;
        def errorStr = "登录失败";
        try {
            def username = params.username;
            def password = params.password;

            if (!username || !password) {
                errorStr = "请填写完整";
            } else {
                def trackUser = TrackUser.findByUsername(username);
                if (!trackUser) {
                    errorStr = "用户名不存在";
                } else {
                    password = PasswordUtil.md5Encode(password);
                    if (trackUser.password != password) {
                        errorStr = "密码不正确";
                    } else {
                        session.setAttribute("AdminUsername", username);
                        result = true;
                    }
                }
            }
        } catch (Exception e) {
            log.error(e);
        } finally {
            
        } 
    }
    
}
